package com.red.controller;

import com.red.pojo.entity.User;
import com.red.pojo.model.LoginUser;
import com.red.service.IUserService;
import com.red.util.HttpStatusUtil;
import com.red.pojo.Result;
import com.red.util.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

@RestController
@RequestMapping("/user/profile")
public class ProfileController {

    @Autowired
    private IUserService userService;

    @GetMapping("/")
    public Result profile(HttpServletRequest request) {
        LoginUser loginUser = JWTUtil.getPayload(request.getHeader("token"), LoginUser.class);

        if (loginUser != null) {
            User user = userService.selectUserByID(loginUser.getUserID());
            return new Result(HttpStatusUtil.SUCCESS, "获取成功", user);
        }

        return new Result(HttpStatusUtil.ERROR, "获取失败");
    }

    @PutMapping()
    public Result update(@RequestBody User user, HttpServletRequest request) {
        LoginUser loginUser = JWTUtil.getLoginUser(request);
        user.setUserId(loginUser.getUserID());
        return userService.updateProfile(user);
    }

    @PostMapping("/photo")
    public Result uploadPhoto(@RequestParam MultipartFile file, HttpServletRequest request) {
        String[] typeList = {"png", "jpg"};

        String fileType = file.getOriginalFilename().split("\\.")[1];

        boolean pass = false;

        for (String type : typeList) {
            if (fileType.equals(type)) {
                pass = true;
                break;
            }
        }

        if (!pass) {
            return Result.error("文件类型错误");
        }

        LoginUser loginUser = JWTUtil.getLoginUser(request);

        String folderName = String.valueOf(loginUser.getUserID());

        String path = request.getServletContext().getRealPath("/upload/user/" + folderName + "/");

        File realPath = new File(path);

        if (!realPath.exists()) {
            if (!realPath.mkdirs()) {
                return Result.error();
            }
        }

        try {
            file.transferTo(new File(realPath + "/" + "profile." + fileType));
        } catch (IOException e) {
            e.printStackTrace();
            return Result.error("上传失败");
        }

        User user = new User();
        user.setUserId(loginUser.getUserID());
        user.setProfile("/upload/user/" + folderName + "/" + "profile." + fileType);

        userService.updateUser(user);

        return Result.success("上传成功");
    }

}
